package net.freebytes.ssmp.controller;

import net.freebytes.ssmp.entity.OperLog;
import net.freebytes.ssmp.entity.Permission;
import net.freebytes.ssmp.entity.Role;
import net.freebytes.ssmp.entity.User;
import net.freebytes.ssmp.service.OperLogService;
import net.freebytes.ssmp.service.PermService;
import net.freebytes.ssmp.service.RolePermService;
import net.freebytes.ssmp.service.RoleService;
import net.freebytes.ssmp.util.CommonUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 测试例子
 *
 * @author 千里明月
 * @date 2021/7/19
 **/
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermService permService;
    @Autowired
    private OperLogService logService;
    @Autowired
    private RolePermService rolePermService;

    @RequiresRoles("admin")
    @GetMapping("/admin")
    @ResponseBody
    public String admin() {
        return "admin角色可访问";
    }

    @RequiresRoles("user")
    @GetMapping("/user")
    @ResponseBody
    public String user() {
        return "user角色可访问";
    }

    @RequiresPermissions("query")
    @GetMapping("/query")
    @ResponseBody
    public String query() {
        return "query权限可访问";
    }

    @RequiresPermissions("insert")
    @GetMapping("/insert")
    @ResponseBody
    public String add() {
        return "insert 权限可访问!";
    }


    @GetMapping("/deleteCache")
    public void deleteCache() {
        roleService.deleteCache(CommonUtil.currentUser().getId());
        permService.deleteCache(CommonUtil.currentUser().getId());
    }

    @GetMapping("/insertLog")
    public void insertLog() {
        OperLog operLog = new OperLog();
        operLog.setOperParam("21");
        logService.insertOperlog(operLog);
    }

    @GetMapping("/getPermissionByRoleId")
    public List<Permission> getPermissionByRoleId() {
        User user = CommonUtil.currentUser();
        List<Role> roles = roleService.cacheRoleByUserId(user.getId());
        List<String> roleIds = roles.stream().map(Role::getId).collect(Collectors.toList());
        return permService.getBaseMapper().getPermissionByRoleId(roleIds);
    }

}
